package cn.liutao.dish.api;

import cn.hutool.core.util.StrUtil;
import cn.liutao.common.entity.Validation;
import cn.liutao.common.enums.CommonEnum;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.common.utils.ValidUtil;
import cn.liutao.dish.entity.param.DishParam;
import cn.liutao.dish.entity.po.Dish;
import cn.liutao.dish.entity.vo.DishVo;
import cn.liutao.dish.service.DishService;
import com.mybatisflex.core.paginate.Page;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liutao
 * @Description 菜品Api
 * @date 2023/10/31 17:03
 * @Version 1.0
 */
@WebServlet("/dish")
@Slf4j
public class DishServlet extends HttpServlet {
    private DishService dishService;

    @Override
    public void init() throws ServletException {
        dishService = DishService.getInstance();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  {
        Dish dish = ServletUtils.getQueryParam(req, Dish.class);
        Page<DishVo> page  = dishService.selectByList(dish);
        List<DishVo> collect = page.getRecords().stream().map(dishVo -> {
            if (StrUtil.isBlank(dishVo.getImg())) dishVo.setImg(CommonEnum.DEFAULT_DISH_IMAGE.getValue());
            return dishVo;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        ServletUtils.ok(resp,page);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        DishParam dish = ServletUtils.getBodyParam(req, DishParam.class);
        ValidUtil.validated(dish,Validation.AddGroup.class);
        dishService.insert(dish);
        ServletUtils.ok(resp,"添加成功");
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
        DishParam dish = ServletUtils.getBodyParam(req, DishParam.class);
        ValidUtil.validated(dish,Validation.EditGroup.class);
        dishService.updateById(dish);
        ServletUtils.ok(resp,"修改成功");
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)  {
        List<String> ids = ServletUtils.getQueryParams(req, "id");
        for (String id : ids) {
            dishService.deleteById(Integer.valueOf(id));
        }
        ServletUtils.ok(resp,"删除成功");
    }
}
